let timer = null;//倒计时全局变量
let count = 60;//每60s调用一次
function up(n) {
  return n < 10 ? '0' + n : n
}
//验证码是否合法
function regPhone(phone) {
  return /^[1][3,4,5,7,8,9][0-9]{9}$/.test(phone)
}
export default {
  data() {
    return {
      phone: '',//手机号码
      code: '',//验证码
      isSendCode: false,
      countText: '发送验证码',//倒计时提示内容
    }
  },
  computed: {
    //手机和验证码
    isBtn() {
      return this.phone.length !== 11 || this.code.length !== 6
    }
  },
  methods: {
    smsLogin() {
      return new Promise(resolve => {
        uni.request({
          url: 'http://redcrossadmin.isaw.top/api/login/LoginBySms', //仅为示例，并非真实接口地址。
          data: {
            phone: this.phone,
            smscode: this.code
          },
          header: {},
          success: (res) => {
            if (res.data.code == 1) {
              //存储
              var userEntity = {
                userId: res.data.data.userId,
                nickName: res.data.data.nickName,
                token: res.data.data.token
              };
              uni.setStorageSync('userInfo', userEntity);
              uni.switchTab({
                url: '/pages/my/my',
              })

            } else {
              uni.showToast({
                title: res.data.msg,
                duration: 2000
              });
              return;
            }
          }
        });
      }).catch((e) => { });
    },
    getSmsCode() {
      var that = this;
      return new Promise((resolve) => {
        uni.request({
          url: "http://redcrossadmin.isaw.top/api/Login/GetSmsCode", //仅为示例，并非真实接口地址。
          data: {
            phone: this.phone
          },
          method: "GET",
          success: (res) => {
            if (res.data.code == 1) {
              that.startCountDown();
            }
          },
        });
      }).catch((e) => {
        that.isSendCode = false
      });
    },
    startCountDown() {
      timer = setInterval(() => {
        if (count > 0) {
          this.isSendCode = true
          count--
          this.countText = `${up(count)}s`
        } else {
          clearInterval(timer)
          count = 60
          this.countText = `发送验证码`
          this.isSendCode = false
        }
      }, 1000)
    },
    //验证手机之类
    isSend() {
      if (!this.phone.length) {
        uni.showToast({
          title: '请输入手机号码',
          duration: 2000,
          icon: 'none'
        });
        return false
      }
      if (!regPhone(this.phone)) {
        uni.showToast({
          title: '手机号码不合法',
          duration: 2000,
          icon: 'none'
        });
        return false
      }
      return true
    },
    //发送验证码
    onSendCode() {
      if (this.isSend()) {
        this.isSendCode = true;
        this.code="";
        this.getSmsCode();
      }
    },
  },
  destroyed() {
    clearInterval(timer)
  }
}
